## takes balance/precision summary object, produces ggplot of 
## arg-geom ("segs"): min to max SB-minus-CR balance (or CR-minus-SB precision)
## arg-geom ("prop.density"): density of 100 sets of 100 trials for "how many is balance/precision better in SB?"
## arg-stat is one of d2.p, hz, vdh, rmse
## arg-by.sb compares (TRUE): 1 SB to 100 CRs
## arg-by.sb compares (FALSE): 100SBs to 100CRs (pairwise same covariates)

plotSBminusCR <- function(bp.summ, stat, geom = "segs", file.name = NULL, by.sb = TRUE){
  if(!is.null(file.name)){
    pdf(file = file.name)
  }
  lab.mat <- data.frame(st= c("d2.p", "hz", "vdh", "rmse"), seg.lab = c("p-value", "H'Z", "variance", "RMSE"), dens.lab = c("Balanced", "Balanced", "Precise", "Precise"))
  lab.string <- lab.mat[lab.mat$st == stat, "seg.lab"]
  summ.type <- lab.mat[lab.mat$st == stat, "dens.lab"]
  
  bp.summ.tmp <- subset(bp.summ, stat.name == stat)
  
  if(geom == "segs"){
    if(by.sb == TRUE){
      y.var <- "sim.sb"
    }else{
      y.var <- "sim.cr"
    }
    if(summ.type == "Balanced"){
      x.string <- paste("(SB ", lab.string, ") - (CR ", lab.string, ")\n100 CR's per SB", sep="")
      vline.at <- 0
      mainTitle <- "Balance"
    }
    if(summ.type == "Precise"){
      x.string <- paste("(CR ", lab.string, ") - (SB ", lab.string, ")\n100 CR's per SB", sep="")
      vline.at <- 0
      mainTitle <- "Precision"
      bp.summ.tmp$min <- -bp.summ.tmp$min
      bp.summ.tmp$max <- -bp.summ.tmp$max
      bp.summ.tmp$median <- -bp.summ.tmp$median
    }
    bp.summ.tmp$ordersimby <- rank(bp.summ.tmp[ , "median"])
    
    print(ggplot(data = bp.summ.tmp, aes(x=min, y = ordersimby)) + geom_segment(aes(xend=max, yend=ordersimby), color = I("grey")) + geom_point(aes(x=median)) + scale_y_discrete("SB Experiment", breaks = NULL) + scale_x_continuous(x.string) + geom_vline(xintercept=vline.at, linetype = 2) + opts(title = mainTitle))
  }
  
  if(geom == "prop.density" && summ.type == "Precise"){
    my.st <- "1-propSBsmaller"
    print(ggplot(data = subset(bp.summ, stat.name == stat), aes_string(x=my.st#propSBsmaller
                                                                       )) + geom_density(trim = TRUE)+ scale_y_discrete("Density of 100 sets of 100 experiments") + xlab(paste("Proportion of Trials in which SB more ", summ.type, " than CR", sep="")) + geom_vline(xintercept=.5, linetype = 2) +xlim(0,1) + opts(title = "Precision")) 
  }
  if(geom == "prop.density" && summ.type == "Balanced"){
    print(ggplot(data = subset(bp.summ, stat.name == stat), aes(x=1-propSBsmaller)) + geom_density(trim = TRUE)+ scale_y_discrete("Density of 100 sets of 100 experiments") + xlab(paste("Proportion of Trials in which SB more ", summ.type, " than CR", sep="")) + geom_vline(xintercept=.5, linetype = 2) +xlim(0,1) + opts(title = "Balance")) 
  }
  
  if(!is.null(file.name)){
    dev.off()      
  }
}
